﻿Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Collections.Generic
Imports SISSAT.BusinessLayer.DomainModels
Imports SISSAT.BusinessLayer.Views
Imports SISSAT.WebDevelopment.Views

Namespace [Shared].[UserControls]
    Public Class GradeListControl
        Inherits UserControl
        Implements IGradeListControlView

#Region "Properties"

        Private Property Presenter As GradeListControlPresenter
        Private Property IsReadOnly As Boolean
        Private Property CssClass As String

        Private ReadOnly Property ExaminationTypeId As Integer
            Get
                Dim id As Integer = 0
                Dim etid As String = HttpContext.Current.Request.QueryString("etid")
                If Not String.IsNullOrEmpty(etid) And Integer.TryParse(etid, id) Then
                    ' No logic
                End If

                Return id
            End Get
        End Property

#End Region

#Region "IGradeListControlView Members"

        Public Property AverageGrade As Decimal Implements IGradeListControlView.AverageGrade
        Public Property ErrorMessage As String Implements IGradeListControlView.ErrorMessage
        Public Property RepeaterData As IEnumerable(Of Examination) Implements IGradeListControlView.RepeaterData

        Public ReadOnly Property CurrentUserId As Integer Implements IGradeListControlView.CurrentUserId
            Get
                Return SISSATPageBase.User.Employee.EmployeeId
            End Get
        End Property

        Public ReadOnly Property EmployeeCode As String Implements IGradeListControlView.EmployeeCode
            Get
                Dim code As String = HttpContext.Current.Request.QueryString("code")
                If String.IsNullOrEmpty(code) Then
                    code = SISSATPageBase.User.Employee.EmployeeCode
                    IsReadOnly = True
                End If

                Return code
            End Get
        End Property

        Public ReadOnly Property SelectedValue As Integer Implements IGradeListControlView.SelectedValue
            Get
                Return Convert.ToInt32(GroupDropDownList.SelectedControlValue)
            End Get
        End Property

        Public WriteOnly Property DropDownListDataSource As IEnumerable(Of KeyValuePair(Of String, String)) Implements IGradeListControlView.DropDownListDataSource
            Set(value As IEnumerable(Of KeyValuePair(Of String, String)))
                GroupDropDownList.DataSource = value
            End Set
        End Property

        Public WriteOnly Property RepeaterDataSource As IEnumerable(Of ExaminationType) Implements IGradeListControlView.RepeaterDataSource
            Set(value As IEnumerable(Of ExaminationType))
                GradeRepeater.DataSource = value
                GradeRepeater.DataBind()
            End Set
        End Property

        Public ReadOnly Property ScheduleId As Integer Implements IGradeListControlView.ScheduleId
            Get
                Return Convert.ToInt32(HttpContext.Current.Request.QueryString("scid"))
            End Get
        End Property

        Public Event OnInitialization() Implements IGradeListControlView.OnInitialization
        Public Event OnSelectedIndexChange() Implements IGradeListControlView.OnSelectedIndexChange
        Public Event OnSubmit(createItems As DataTable, updateItems As DataTable) Implements IGradeListControlView.OnSubmit

#End Region
        
#Region "Methods"

        Private Sub InitializeComponents()
            If Me.ExaminationTypeId > 0 Then
                GroupDropDownList.SelectedControlValue = Convert.ToString(Me.ExaminationTypeId)
                GroupDropDownList.AutoPostBack = False
                GroupDropDownList.IsReadOnly = True
            End If

            RaiseEvent OnSelectedIndexChange()

            Dim cssClassFormat As String = "minitextbox {0} alignr"
            ButtonPanel.Visible = Not IsReadOnly
            Dim attendanceExpression As String = ConfigurationManager.AppSettings("YearRegEx")
            Dim css As String = Convert.ToString(IIf(IsReadOnly, _
                                                     String.Format(cssClassFormat, "readonly"), _
                                                     String.Format(cssClassFormat, "req")))


            For Each item As RepeaterItem In GradeRepeater.Items
                Dim typeIdHiddenField As HiddenField = CType(item.FindControl("TypeIdhiddenField"), HiddenField)
                Dim examIdHiddenField As HiddenField = CType(item.FindControl("ExamIdHiddenField"), HiddenField)
                Dim gradeHiddenField As HiddenField = CType(item.FindControl("GradeHiddenField"), HiddenField)
                Dim gradeTextBox As TextBox = CType(item.FindControl("GradeTextBox"), TextBox)

                If Convert.ToInt32(typeIdHiddenField.Value) = 1 Then
                    Dim attendanceRegExValidator As RegularExpressionValidator = _
                        CType(item.FindControl("GradeRegExValidator"), RegularExpressionValidator)
                    attendanceRegExValidator.ValidationExpression = attendanceExpression
                    attendanceRegExValidator.ErrorMessage = "Invalid attendance. (e.g. 1-4)"
                End If

                gradeTextBox.CssClass = css
                gradeTextBox.ReadOnly = IsReadOnly

                Dim entity As Examination = (From data In Me.RepeaterData
                                             Where data.ExaminationType.ExaminationTypeId = Convert.ToInt32(typeIdHiddenField.Value)
                                             Select data).FirstOrDefault()

                If entity IsNot Nothing Then
                    examIdHiddenField.Value = Convert.ToString(entity.ExaminationId)
                    gradeHiddenField.Value = Convert.ToString(entity.Grade)
                    gradeTextBox.Text = gradeHiddenField.Value
                End If
            Next
        End Sub

#End Region

#Region "Events"

        Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
            IsReadOnly = False
            Presenter = New GradeListControlPresenter(Me)
            RaiseEvent OnInitialization()

            InitializeComponents()
        End Sub

        Protected Sub SelectedIndexChanged(ByVal send As Object, ByVal e As System.EventArgs) Handles GroupDropDownList.SelectedIndexChanged
            InitializeComponents()
        End Sub

        Protected Sub SubmitButtonClick(ByVal sender As Object, ByVal e As System.EventArgs) Handles SubmitButton.Click
            Dim createItems As DataTable = Examination.GetDataTable()
            Dim updateItems As DataTable = Examination.GetDataTable()

            Dim items As New List(Of KeyValuePair(Of Integer, Decimal))

            For Each item As RepeaterItem In GradeRepeater.Items
                Dim typeIdhiddenField As HiddenField = CType(item.FindControl("TypeIdhiddenField"), HiddenField)
                Dim examIdHiddenField As HiddenField = CType(item.FindControl("ExamIdHiddenField"), HiddenField)
                Dim gradeHiddenField As HiddenField = CType(item.FindControl("GradeHiddenField"), HiddenField)
                Dim gradeTextBox As TextBox = CType(item.FindControl("GradeTextBox"), TextBox)

                Dim examinationTypeId As Integer = Convert.ToInt32(typeIdhiddenField.Value)
                Dim inputGrade As Decimal = _
                    Convert.ToDecimal(IIf(String.IsNullOrEmpty(gradeTextBox.Text), "0.00", gradeTextBox.Text))
                Dim previousGrade As Decimal = _
                    Convert.ToDecimal(IIf(String.IsNullOrEmpty(gradeHiddenField.Value), "0.00", gradeHiddenField.Value))

                If previousGrade = 0D AndAlso inputGrade > previousGrade Then
                    Dim groupId As Integer = Convert.ToInt32(Me.SelectedValue)
                    createItems.Rows.Add(0, Me.ScheduleId, examinationTypeId, groupId, Me.EmployeeCode, inputGrade)
                ElseIf previousGrade > 0D AndAlso Not (inputGrade = previousGrade) Then
                    Dim groupId As Integer = Convert.ToInt32(Me.SelectedValue)
                    Dim examId As Integer = Convert.ToInt32(examIdHiddenField.Value)

                    updateItems.Rows.Add(examId, Me.ScheduleId, examinationTypeId, groupId, Me.EmployeeCode, inputGrade)
                End If
            Next

            RaiseEvent OnSubmit(createItems, updateItems)

            If String.IsNullOrEmpty(Me.ErrorMessage) Then
                Dim url As String = String.Format("/Pages/Home/Subjects.aspx?scid={0}", Me.ScheduleId)
                HttpContext.Current.Response.Redirect(url)
            End If
        End Sub

#End Region

    End Class
End Namespace
